<template>
  <div class="image-upload-root" :class="{inline: inline}">
    <!--已有图片-->
    <div class="img inline" :style="getImgStylus(src)" v-for="src in srcs" :key="src" @click="onImageClick(src)">
      <div class="delete-btn" @click.stop.prevent="onDeleteImage(src)">
        <i class="iconfont icon-close"></i>
      </div>
    </div>
    <!--添加图片-->
    <div class="img add inline" v-show="srcs.length < maxCount">
      <i class="iconfont icon-add"></i>
      <input type="file" class="file-input" @change.prevent="onFile">
    </div>

  </div>
</template>
  
<script>
  import api from '@/api'

  export default {
    name: '',

    props: {
      inline: {
        type: Boolean,
        default: false
      },
      maxCount: {
        type: Number,
        default: 10
      },

      maxSize: {
        type: Number,
        default: 1 // 单位M
      },
      images: {
        type: Array,
        default () {
          return [
            // 'http://pic44.nipic.com/20140721/11624852_001107119409_2.jpg'
          ]
        }
      }
    },

    data () {
      return {
        srcs: this.images,
        uploading: false
      }
    },

    computed: {
      isTooMuch () {
        return this.srcs.length > this.maxCount
      }
    },

    mounted () {
      this.checkProps()
    },

    methods: {
      checkProps () {
        if (this.isTooMuch) {
          throw new Error('图片数量超过限制')
        }
      },

      onImageClick (src) {
        this.$PreviewImage.show(src)
      },

      /*
       * 监听图片上传事件
       */
      onFile (event) {
        let input = event.target
        let file = input.files[0]

        // 导入文件类型不合法
        if (!/\.(?:png|jpg|bmp|gif)$/i.test(file.name) || !file.size) {
          this.showError('请上传正确的图片文件')
          throw new Error('图片数量超过限制')
        }
        // 图片过大
        if (file && file.size > this.maxSize * 1024 * 1024) {
          this.showError(`图片大小不能超过${this.maxSize}M`)
          throw new Error('图片过大')
        }
        // 浏览器不支持
        if (!(window.File && window.FileReader && window.FileList && window.Blob)) {
          this.showError(`当前环境不支持图片上传`)
          throw new Error('浏览器不支持')
        }
        var reader = new window.FileReader()

        reader.onerror = (evt) => {
          this.showError(`图片上传出错`)
          throw new Error('图片上传出错')
        }

        // 读取完成
        reader.onloadend = async (evt) => {
          if (this.uploading) return this.showError('正在上传, 请稍后重试')
          if (evt.target.readyState !== window.FileReader.DONE) return
          this.uploading = true
          let res = await api.upload.image(evt.target.result)
          this.srcs.push(res.data.url)
          this.emitImages(this.srcs)
          input.value = ''
          this.uploading = false
        }

        reader.readAsArrayBuffer(file)
      },

      showError (str) {
        return this.$Alert.show(str)
      },

      getImgStylus (src) {
        return {
          backgroundImage: `url('${src}')`
        }
      },

      async onDeleteImage (src) {
        let isConfirm = window.confirm('确定要删除这张图片?')
        if (!isConfirm) return
        let index = this.srcs.indexOf(src)
        this.srcs.splice(index, 1)
        this.emitImages(this.srcs)
      },

      emitImages (images) {
        this.emit('input:images', images)
      },

      emit (...params) {
        this.$emit(...params)
      }
    }
  }
</script>

<style lang="stylus" scoped>
.image-upload-root
  width 100%
  text-align left
  .img
    position relative
    width 2rem
    height 2rem
    box-sizing border-box
    background #fff
    margin-left 0.2rem
    margin-bottom 0.2rem

    .delete-btn
      position absolute
      left 100%
      top 0
      transform translate(-50%, -50%)
      width 0.5rem
      height 0.5rem
      line-height 0.5rem
      text-align center
      background red
      border-radius 1rem
      .iconfont
        display inline-block
        color #fff
        font-size 0.4rem
    &.add
      border 0.05rem solid #ccc
      .file-input
        display block
        position absolute
        left 0
        top 0
        width 100%
        height 100%
        opacity 0
      .iconfont
        display block
        width 1rem
        left 1rem
        position absolute
        top 50%
        left 50%
        transform translate(-50%, -50%)
        font-size 1rem
        color #ccc

.inline
  display inline-block
</style>
